/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package client;
import model.*;
import java.sql.*;
import view.LoginView;

/**
 *
 * @author Tobias
 */
public class Login {
    //get instance of connected database
    private boolean connStatus = DBConnection.getInstance().getConnectionActive();

    //set whether a user is logged in
    private boolean logStatus = false;
    private ResultSet result = null;
    private static Login instance = null;
    private String user = null;
    private String access = null;

    public Login() {

    }

    /**
     * 3. System verifies user information.
     *
     * @param user username to be verified
     * @param pwd password of user
     * @param access users level of access
     */
    public void verifyLogin(String username, String pwd, String acc) {
        access = acc;
        if (connStatus) {
            try {
                QueryModel query = new QueryModel();
                result = query.checkUserLogin(username, pwd, access);
                user = username;
                setUser();
            } catch (Exception e) {
               ClientView.printMessage("Error: login user fail\n");
               ClientView.printMessage(e.getMessage());
            }
        }
    }

    /**
     * 4. System sets user as logged in status
     */
    public void setUser() {
        try {
            if (!result.next() && result.getRow() == 0) {
                logStatus = false;
            } else {
                    Client.getInstance().setUser(user);
                logStatus = true;
            }
        } catch (SQLException e) {
            ClientView.printMessage("Error: setting user status fail\n ");
            ClientView.printMessage(e.getMessage());
        }
    }

    /**
     * 5. System notifies actor they are logged in
     */
    public boolean checkStatus() {
        return logStatus;
    }

    public static void loadLoginUserView(String type) {
        ClientView view = ClientView.getInstance();
        LoginView lv = new LoginView(view, type);
     	lv.pack();
        view.centerWindow(lv);
        lv.setVisible(true);
    }

    public static Login getInstance() {
        if (instance == null) {
            instance = new Login();
        }
        return instance;
    }

}
